﻿using Artech.Common;
using Artech.Common.Properties;
using Microsoft.Practices.Unity.Utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;

namespace Artech.Core
{
    /// <summary>
    /// A collection of <see cref="ContextItem"/>.
    /// </summary>
    public class ContextItemCollection: ICloneable
    {
        private Dictionary<string, ContextItem> items = new Dictionary<string, ContextItem>();
        private object syncHelper = new object();

        public ContextItemCollection(IEnumerable<ContextItem> contextItems = null)
        {
            if (null != contextItems)
            {
                if (contextItems.GroupBy(item => item.Key).Any(item => item.Count() > 1))
                {
                    throw new ArgumentException(ResourceUtility.Format(CoreResources.ExceptionDuplicateContextItemKey), "contextItems");
                }
                foreach (ContextItem item in contextItems)
                {
                    this.Add(item);
                }
            }

            this.Add(new ContextItem(ApplicationContext.Keys.CurrentCulture, Thread.CurrentThread.CurrentCulture.Name), InsertItemBehavior.None);
            this.Add(new ContextItem(ApplicationContext.Keys.CurrentUICulture, Thread.CurrentThread.CurrentUICulture.Name), InsertItemBehavior.None);
            string userName = Thread.CurrentPrincipal.Identity.Name;
            if (null != HttpContext.Current)
            {
                userName = HttpContext.Current.User.Identity.Name;
            }
            this.Add(new ContextItem(ApplicationContext.Keys.UserName, userName), InsertItemBehavior.None);
        }

        /// <summary>
        /// Adds the specified context item.
        /// </summary>
        /// <param name="contextItem">The context item.</param>
        /// <param name="insertItemBehavior">The insert item behavior.</param>
        /// <exception cref="System.ArgumentException">Is thrown if there is a duplicate context itme with the same key.</exception>
        public void Add(ContextItem contextItem, InsertItemBehavior insertItemBehavior = InsertItemBehavior.ThrowException)
        {
            Guard.ArgumentNotNull(contextItem, "contextItem");
            if (items.ContainsKey(contextItem.Key))
            {
                switch (insertItemBehavior)
                    {
                        case InsertItemBehavior.ThrowException: throw new ArgumentException(ResourceUtility.Format(CoreResources.ExceptionDuplicateContextItem, contextItem.Key));
                        case InsertItemBehavior.None: return;
                    }
            }
            lock (syncHelper)
            {
                if (items.ContainsKey(contextItem.Key))
                {
                    switch (insertItemBehavior)
                    {
                        case InsertItemBehavior.ThrowException: throw new ArgumentException(ResourceUtility.Format(CoreResources.ExceptionDuplicateContextItem, contextItem.Key));
                        case InsertItemBehavior.None: return;
                        case InsertItemBehavior.Override: { items.Remove(contextItem.Key); break; }
                    }
                }
                items.Add(contextItem.Key, contextItem);
            }
        }

        /// <summary>
        /// Gets the <see cref="ContextItem"/> with the specified key.
        /// </summary>
        /// <value>
        /// The <see cref="ContextItem"/>.
        /// </value>
        /// <param name="key">The key of context item.</param>
        /// <returns>The <see cref="ContextItem"/>.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        public ContextItem this[string key]
        {
            get
            {
                Guard.ArgumentNotNullOrEmpty(key, "key");
                ContextItem contextItem;
                if (items.TryGetValue(key, out contextItem))
                {
                    return contextItem;
                }
                throw new ArgumentOutOfRangeException(ResourceUtility.Format(CoreResources.ExceptionContextItemNotExists, key));
            }
        }

        /// <summary>
        /// Tries the get value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="contextItem">The context item.</param>
        /// <returns>A <see cref="bool"/> value indicating whether a <see cref="ContextItem"/> exists.</returns>
        public bool TryGetValue(string key, out ContextItem contextItem)
        {
            Guard.ArgumentNotNullOrEmpty(key, "key");
            return items.TryGetValue(key, out contextItem);
        }

        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>
        /// A new object that is a copy of this instance.
        /// </returns>
        object ICloneable.Clone()
        {
            return this.Clone();
        }

        /// <summary>
        /// Clones this instance.
        /// </summary>
        /// <returns>A new <see cref="ContextItemCollection"/>.</returns>
        public ContextItemCollection Clone()
        {
            ContextItemCollection newCollection = new ContextItemCollection();
            foreach (var item in items)
            {
                newCollection.Add(item.Value.Clone(), InsertItemBehavior.Override);
            }
            return newCollection;
        }

        /// <summary>
        /// Remove all <see cref="ContextItem"/>.
        /// </summary>
        public void Clear()
        {
            items.Clear();
        }

        /// <summary>
        /// Convert to arry of <see cref="ContextItem"/>.
        /// </summary>
        /// <returns>A arry of <see cref="ContextItem"/>.</returns>
        public ContextItem[] ToArray()
        {
            return items.Values.ToArray();
        }
    }
}
